home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 15198 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.9 KB  |  58 lines

  1. Path: news.primenet.com!jstern
  2. From: jstern@primenet.com (Josh Stern)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: How to initialize array of objects using non-void constructor?
  5. Date: 3 Apr 1996 21:57:02 -0700
  6. Organization: Primenet Services for the Internet
  7. Sender: root@primenet.com
  8. Message-ID: <4jvkqu$8kp@nnrp1.news.primenet.com>
  9. References: <4jbuo5$mcb@newshost.lanl.gov> <315C8F65.78D5@aai.arco.com> <315F5E13.799D1B33@alcyone.com> <DpAoG2.nCn@undergrad.math.uwaterloo.ca>
  10. X-Posted-By: jstern@usr1.primenet.com
  11.  
  12. Steve Kettle <sckettle@undergrad.math.uwaterloo.ca> wrote:
  13. >Erik Max Francis  <max@alcyone.com> wrote:
  14. >>Brian Leach wrote:
  15. >>> Liang Lu wrote:
  16.  
  17. >>> Sorry Liang, it is not possible. The language does not allow for
  18. >>> non-default
  19. >>> constructors for arrays of objects.
  20.  
  21. The language basically provides the placement form
  22. of operator new for this purpose (see below).
  23.  
  24. >>Nonsense; see Ellis & Stroustrup, 12.6.1.  Using non-default constructors for
  25. >>initializing an array is much the same as one would expect (using the example
  26. >>above):
  27. >>
  28. >>    Table object[3] = { object(1), object(1), object(2) };
  29.  
  30. >But you can't for an array on the heap.  
  31.  
  32. Yes you can, it goes like this:
  33.  
  34. #include <new.h> // for placement new
  35.  
  36. Table* tptr = malloc(sizeof(Table)*num_tables);
  37. if (!tptr) exit(1); // malloc failed
  38. for (int i=0; i < num_tables; i++) 
  39.    new (tptr++) Table(val); // example for single arg constructor
  40.                             // arbitrary number of args possible
  41.  
  42. There is also a do-nothing placement form of delete
  43. that simply calls the destructor for the objects.
  44. For convenience, check out the templates Construct
  45. and Destroy in the file defalloc.h of the HP implementation
  46. of STL.
  47.  
  48.  
  49. - Josh
  50.  
  51.  
  52.  
  53. --
  54. -------------------------------------------------------------------------------
  55. jstern
  56. jstern@primenet.com
  57. -------------------------------------------------------------------------------
  58.